package org.icnmasjid.member.webapp.action;

import java.beans.PropertyEditor;
import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.displaytag.pagination.PaginatedList;
import org.displaytag.properties.SortOrderEnum;

import org.icnmasjid.member.Constants;
import org.icnmasjid.member.model.PaymentCategory;
import org.icnmasjid.member.model.Role;
import org.icnmasjid.member.model.SubOrg;
import org.icnmasjid.member.model.User;
import org.icnmasjid.member.service.MailEngine;
import org.icnmasjid.member.service.Manager;
import org.icnmasjid.member.service.UserManager;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.CustomNumberEditor;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import sun.security.action.GetLongAction;

/**
 * Implementation of <strong>SimpleFormController</strong> that contains
 * convenience methods for subclasses.  For example, getting the current
 * user and saving messages/errors. This class is intended to
 * be a base class for all Form controllers.
 *
 * <p><a href="BaseFormController.java.html"><i>View Source</i></a></p>
 *
 * @author <a href="mailto:matt@raibledesigns.com">Matt Raible</a>
 */
public class BaseFormController extends SimpleFormController {
    protected final transient Log log = LogFactory.getLog(getClass());
    protected final String MESSAGES_KEY = "successMessages";
    private UserManager userManager = null;
    protected MailEngine mailEngine = null;
    protected SimpleMailMessage message = null;
    protected String templateName = null;
    protected String cancelView;
	protected Manager manager = null;
	private org.icnmasjid.member.service.RoleManager roleManager = null;
	private org.icnmasjid.member.service.LookupManager lookupManager = null;

    public void setUserManager(UserManager userManager) {
        this.userManager = userManager;
    }

    public UserManager getUserManager() {
        return this.userManager;
    }

    public void saveMessage(HttpServletRequest request, String msg) {
        List messages = (List) request.getSession().getAttribute(MESSAGES_KEY);

        if (messages == null) {
            messages = new ArrayList();
        }

        messages.add(msg);
        request.getSession().setAttribute(MESSAGES_KEY, messages);
    }

    /**
     * Convenience method for getting a i18n key's value.  Calling
     * getMessageSourceAccessor() is used because the RequestContext variable
     * is not set in unit tests b/c there's no DispatchServlet Request.
     *
     * @param msgKey
     * @param locale the current locale
     * @return
     */
    public String getText(String msgKey, Locale locale) {
        return getMessageSourceAccessor().getMessage(msgKey, locale);
    }

    /**
     * Convenient method for getting a i18n key's value with a single
     * string argument.
     *
     * @param msgKey
     * @param arg
     * @param locale the current locale
     * @return
     */
    public String getText(String msgKey, String arg, Locale locale) {
        return getText(msgKey, new Object[] { arg }, locale);
    }

    /**
     * Convenience method for getting a i18n key's value with arguments.
     *
     * @param msgKey
     * @param args
     * @param locale the current locale
     * @return
     */
    public String getText(String msgKey, Object[] args, Locale locale) {
        return getMessageSourceAccessor().getMessage(msgKey, args, locale);
    }

    /**
     * Convenience method to get the Configuration HashMap
     * from the servlet context.
     *
     * @return the user's populated form from the session
     */
    public Map getConfiguration() {
        Map config =
            (HashMap) getServletContext().getAttribute(Constants.CONFIG);

        // so unit tests don't puke when nothing's been set
        if (config == null) {
            return new HashMap();
        }

        return config;
    }

    /**
     * Default behavior for FormControllers - redirect to the successView
     * when the cancel button has been pressed.
     */
    public ModelAndView processFormSubmission(HttpServletRequest request,
                                              HttpServletResponse response,
                                              Object command,
                                              BindException errors)
    throws Exception {
        if (request.getParameter("cancel") != null) {
            return new ModelAndView(getCancelView());
        }

        return super.processFormSubmission(request, response, command, errors);
    }

    /**
     * Set up a custom property editor for converting form inputs to real objects
     */
    protected void initBinder(HttpServletRequest request,
                              ServletRequestDataBinder binder) {
    	binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
        binder.registerCustomEditor(Integer.class, null,
                                    new CustomNumberEditor(Integer.class, null, true));
        binder.registerCustomEditor(Long.class, null,
                                    new CustomNumberEditor(Long.class, null, true));
        binder.registerCustomEditor(Double.class, null,
                new CustomNumberEditor(Double.class, null, true));
        binder.registerCustomEditor(byte[].class,
                                    new ByteArrayMultipartFileEditor());
        SimpleDateFormat dateFormat =
            new SimpleDateFormat(getText("date.format", request.getLocale()));
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, null,
                                    new CustomDateEditor(dateFormat, true));
        binder.registerCustomEditor(
                java.sql.Date.class,
                new PropertyEditorSupport() {
                    SimpleDateFormat dateFormat =
                        new SimpleDateFormat("MM/dd/yyyy");

                    public void setAsText(String text) throws IllegalArgumentException {
                        if ( StringUtils.isNotBlank(text) ) {
                            try {
                                dateFormat.setLenient(false);
                                setValue(new java.sql.Date(dateFormat.parse(text).getTime()));
                            } catch (ParseException e) {
                                throw new IllegalArgumentException("Could not parse date: " + e.getMessage());
                            }
                        }
                    }

                    public String getAsText() {
                        java.sql.Date value = (java.sql.Date) getValue();
                        return (value != null ? this.dateFormat.format(value) : "");
                    }
                }
        );

        binder.registerCustomEditor(String.class,"phoneHome",new StringTrimmerEditor("()- ",true));
        binder.registerCustomEditor(String.class,"phoneWork",new StringTrimmerEditor("()- ",true));
        binder.registerCustomEditor(String.class,"phoneMobile",new StringTrimmerEditor("()- ",true));
        binder.registerCustomEditor(String.class,"phoneFax",new StringTrimmerEditor("()- ",true));
        binder.registerCustomEditor(String.class,"phone",new StringTrimmerEditor("()- ",true));

        binder.registerCustomEditor(
                SubOrg.class,
                new PropertyEditorSupport() {
	                public void setAsText(String text) throws IllegalArgumentException {
	                	if ( StringUtils.isNotBlank(text)) {
	                		setValue(getManager().getObject(SubOrg.class, Integer.valueOf(text)));
	                	} else {
	                		setValue(new SubOrg());
	                	}
	                }

	                @Override
	                public String getAsText() {
	                	if ( getValue() != null ) {
	                		return ((SubOrg)getValue()).getFullName();
	                	} else {
	                		return "";
	                	}
	                }
                }
        );

        binder.registerCustomEditor(
                Role.class,
                new PropertyEditorSupport() {
	                public void setAsText(String text) throws IllegalArgumentException {
	                	if ( StringUtils.isNotBlank(text)) {
	                		setValue(getManager().getObject(Role.class, Long.valueOf(text)));
	                	} else {
	                		setValue(new Role());
	                	}
	                }

	                @Override
	                public String getAsText() {
	                	if ( getValue() != null ) {
	                		return ((Role)getValue()).getName();
	                	} else {
	                		return "";
	                	}
	                }
                }
        );

        binder.registerCustomEditor(
                PaymentCategory.class,
                new PropertyEditorSupport() {
	                public void setAsText(String text) throws IllegalArgumentException {
	                	if ( StringUtils.isNotBlank(text)) {
	                		setValue(getManager().getObject(PaymentCategory.class, Integer.valueOf(text)));
	                	} else {
	                		setValue(new PaymentCategory());
	                	}
	                }

	                @Override
	                public String getAsText() {
	                	if ( getValue() != null ) {
	                		return ((PaymentCategory)getValue()).getName();
	                	} else {
	                		return "";
	                	}

	                }
                }
        );


    }

    /**
     * Convenience message to send messages to users, includes app URL as footer.
     * @param user
     * @param msg
     * @param url
     */
    protected void sendUserMessage(User user, String msg, String url) {
        if (log.isDebugEnabled()) {
            log.debug("sending e-mail to user [" + user.getEmail() + "]...");
        }

        message.setTo(user.getFullName() + "<" + user.getEmail() + ">");

        Map model = new HashMap();
        model.put("user", user);

        // TODO: once you figure out how to get the global resource bundle in
        // WebWork, then figure it out here too.  In the meantime, the Username
        // and Password labels are hard-coded into the template.
        // model.put("bundle", getTexts());
        model.put("message", msg);
        model.put("applicationURL", url);
        mailEngine.sendMessage(message, templateName, model);
    }

    public void setMailEngine(MailEngine mailEngine) {
        this.mailEngine = mailEngine;
    }

    public void setMessage(SimpleMailMessage message) {
        this.message = message;
    }

    public void setTemplateName(String templateName) {
        this.templateName = templateName;
    }
    /**
     * Indicates what view to use when the cancel button has been pressed.
     */
    public final void setCancelView(String cancelView) {
        this.cancelView = cancelView;
    }

    public final String getCancelView() {
        // Default to successView if cancelView is invalid
        if (this.cancelView == null || this.cancelView.length()==0) {
            return getSuccessView();
        }
        return this.cancelView;
    }

    @Override
    protected Map referenceData(HttpServletRequest request, Object command, Errors errors) throws Exception {
    	Map map = super.referenceData(request, command, errors);
    	if ( map == null ) {
    		map = new HashMap();
    	}
    	map.put("subOrgs", getRoleManager().getSubOrgs());
    	map.put("roles", getRoleManager().getRoles(new Role()));
    	map.put("paymentCategories", getLookupManager().getPaymentCategories() );
    	return map;
    }

	public Manager getManager() {
		return manager;
	}

	public void setManager(Manager manager) {
		this.manager = manager;
	}

    public static PaginatedList createPaginatedList(
    		final List list,
    		final int fullListSize,
    		final int objectsPerPage,
    		final int pageNumber,
    		final String sortCriteria,
    		final String sortDirection
    ) {
    	return new PaginatedList() {
    		public int getFullListSize() {
    			return fullListSize;
    		}

    		public List getList() {
    			return list;
    		}

    		public int getObjectsPerPage() {
    			return objectsPerPage;
    		}

    		public int getPageNumber() {
    			return pageNumber;
    		}

    		public String getSearchId() {
    			return null;
    		}

    		public String getSortCriterion() {
    			return sortCriteria;
    		}

    		public SortOrderEnum getSortDirection() {
    			return SortOrderEnum.fromName("desc".equals(sortDirection) ? "descending" : "ascending");
    		}
    	};
    }

	public org.icnmasjid.member.service.RoleManager getRoleManager() {
		return roleManager;
	}

	public void setRoleManager(org.icnmasjid.member.service.RoleManager roleManager) {
		this.roleManager = roleManager;
	}

	public org.icnmasjid.member.service.LookupManager getLookupManager() {
		return lookupManager;
	}

	public void setLookupManager(
			org.icnmasjid.member.service.LookupManager lookupManager) {
		this.lookupManager = lookupManager;
	}

}
